import * as echarts from 'echarts'
import proces from './process.vue'
import { connectWebSocket } from '@/utils/web-socket.js'
import { callJcmxApi, saveAsJcmxApi, updateJcmxApi } from '../api/index'
import SaveModel from '@/views/components/model/index.vue'
export default {
  components: {
    proces,
    SaveModel
  },
  data() {
    return {
      formInline: {
        demand: '',
        targetArea: '',
        sample: ''
      },
      labelPosition: 'right',
      dialogTitle: '',
      formLabelAlign: {
        name: '',
        region: '',
        type: ''
      },
      tableData: [],
      currentPage3: 5,
      trainId: '',
      test: '',
      socketUrl: window.ipConfig.decision,
      instructionLog: '',
      countpush: 0,
      chartDataX: [],
      TrainingsetList: [],
      TestsetList: [],
      SingleAveragePrecisionRate: '',
      OverallAccuracy: '',
      DecisionSpeed: '',
      TrainingTime: '',
      startMxStaut: false,
      Mask: null,
      trainName: '',
      testName: '',
      isModelSave: true
    }
  },
  computed: {},
  created() { },
  mounted() {
    this.initCharts(
      'topCharts',
      'rgba(133, 141, 200, 1)',
      ['1', '2', '3', '4', '5', '6', '7'],
      ['rgba(90, 98, 159, 0)', 'rgba(133, 141, 200, 0.89)'],
      [140, 232, 101, 264, 90, 340, 250],
      '',
      '训练集准确率',
      '迭代次数'
    )
    this.initCharts(
      'BottomCharts',
      'rgba(133, 200, 190, 1)',
      ['1', '2', '3', '4', '5', '6', '7'],
      ['rgba(90, 98, 159, 0)', 'rgba(133, 200, 190, 0.89)'],
      [140, 232, 101, 264, 90, 340, 250],
      '',
      '测试集准确率',
      '迭代次数'
    ),
      this.connectWs()
  },
  methods: {
    /** 接受子组件按钮回调 */
    decisionCallback(value, radioValue) {
      if (radioValue == 1) {
        // 保存逻辑
        updateJcmxApi(value).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
          } else {
            this.$message.error('操作失败')
          }
        })
      } else {
        // 另存为逻辑
        saveAsJcmxApi(value).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
          } else {
            this.$message.error('操作失败')
          }
        })
      }
    },
    /** 训练及评估 */
    startedTraining() {
      if (
        !this.trainId ||
        this.trainId === '' ||
        !this.test ||
        this.test === ''
      ) {
        this.$message.warning('请将参数配置完整！')
        return
      }
      const ids = {
        mxID: this.$route.query.id,
        csjbh: this.trainId,
        xljBh: this.test
      }
      this.startMxStaut = true
      this.Mask = this.$loading({
        lock: true,
        text: '模型训练中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      callJcmxApi(ids).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
          this.Mask.close()
          this.startMxStaut = false
        }
      })
    },
    connectWs() {
      connectWebSocket({
        url: window.ipConfig.wsUrl,
        topic: [
          // 订阅决策模型训练集
          {
            name: '/topic/udpJcmxData',
            callback: res => {
              if (this.Mask != null) {
                this.Mask.close()
              }
              // 开始训练按钮置灰
              this.startMxStaut = true
              const datalist = JSON.parse(res.body)
              if (Array.isArray(datalist)) {
                // 数据推送完成，右上角展示当前训练结束信息
                if (datalist.length === 4) {
                  this.SingleAveragePrecisionRate = datalist[0]
                  this.OverallAccuracy = datalist[1]
                  this.DecisionSpeed = datalist[2]
                  this.TrainingTime = datalist[3]
                  this.startMxStaut = false
                  this.isModelSave = false
                  // 置空
                  this.countpush = 0
                  this.chartDataX = []
                  this.TrainingsetList = []
                  this.TestsetList = []
                  return
                }

                this.countpush++
                this.chartDataX.push(this.countpush)

                // 处理训练集
                if (datalist.length != 0 && datalist[0]) {
                  this.TrainingsetList.push(datalist[0])
                  this.initCharts(
                    'topCharts',
                    'rgba(133, 141, 200, 1)',
                    this.chartDataX,
                    ['rgba(90, 98, 159, 0)', 'rgba(133, 141, 200, 0.89)'],
                    this.TrainingsetList,
                    '',
                    '训练集准确率',
                    '迭代次数'
                  )
                }
                // 处理测试集
                if (datalist[1]) {
                  this.TestsetList.push(datalist[1])
                  this.initCharts(
                    'BottomCharts',
                    'rgba(133, 200, 190, 1)',
                    this.chartDataX,
                    ['rgba(90, 98, 159, 0)', 'rgba(133, 200, 190, 0.89)'],
                    this.TestsetList,
                    '',
                    '测试集准确率',
                    '迭代次数'
                  )
                }
              }
            }
          }
        ]
      })
    },
    completeCallback(value) {
      if (value.type === 1) {
        this.trainName = value.data[0].jcybjID
        this.trainId = value.data[0].id
      } else {
        this.testName = value.data[0].jcybjID
        this.test = value.data[0].id
      }
    },
    // 模型保存
    handleModalSave() {
      if (this.isModelSave == true) {
        return this.$message.warning('请先训练')
      }
      this.$refs.modelRef.openModal(this.OverallAccuracy, this.DecisionSpeed)
    },
    onSubmit(text) {
      this.$refs.procesRef.dialogVisible = true
      this.dialogTitle = text
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },
    goBack() {
      this.$router.go(-1)
    },
    initCharts(
      eleId,
      color,
      xAxisData,
      seriesColor,
      seriesData,
      titleName,
      yAxisName,
      xAxisName
    ) {
      let chartDom = document.getElementById(eleId)
      let myChart = echarts.init(chartDom)
      let option = {
        color: [color],
        title: {
          text: titleName,
          textStyle: {
            color: '#fff',
            fontSize: 16
          },
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              // backgroundColor: '#fff'
            }
          }
        },
        legend: {
          show: false
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            name: xAxisName,
            boundaryGap: false,
            data: xAxisData,
            nameTextStyle: {
              color: '#fff',
              align: 'right',
              fontSize: 16
            },
            axisLine: {
              lineStyle: {
                color: '#677488'
              }
            },
            axisLabel: {
              textStyle: {
                color: '#fff'
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: yAxisName,
            nameTextStyle: {
              color: '#fff',
              align: 'center',
              fontSize: 16
            },
            splitLine: { show: false },
            axisLine: {
              lineStyle: {
                color: '#677488'
              }
            },
            axisLabel: {
              textStyle: {
                color: '#fff'
              }
            }
          }
        ],
        series: [
          {
            name: 'Line 1',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: seriesColor[1]
                },
                {
                  offset: 1,
                  color: seriesColor[0]
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: seriesData
          }
        ]
      }
      myChart.setOption(option)
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    }
  }
}
